package com.jida.tijian.service;

import com.jida.tijian.domain.Orders;
import com.jida.tijian.dto.ResponseObject;
import com.jida.tijian.exception.TijianAPPException;
import com.jida.tijian.exception.TijianAPPExceptionEnum;
import com.jida.tijian.mapper.OrdersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class OrdersServicelmpl implements OrdersService {
    @Autowired
    OrdersMapper ordersMapper;

    @Override
    public ResponseObject saveOrders(Orders orders){
        //根据体检预约日期和用户号码来判断。若当天用户已经预约过，抛出异常
        int count = ordersMapper.countUserOrdersByDate(orders.getUserId(), orders.getOrderDate());
        if (count > 0) {
            // 用户在当天已有预约，抛出异常
            throw new TijianAPPException(
                TijianAPPExceptionEnum.USER_ALREADY_BOOKED.getCode(),
                TijianAPPExceptionEnum.USER_ALREADY_BOOKED.getMessage()
            );
        }
        
        // 没有预约过，执行插入操作
        ordersMapper.insert(orders);
        return new ResponseObject(ResponseObject.SUCCESS_STATUS, ResponseObject.SUCCESS_DESC);
    }
    
    @Override
    public ResponseObject checkUserDateOrder(String userId, Date orderDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //System.out.println("Service层 - 检查用户预约 - 用户ID: " + userId + ", 日期: " + sdf.format(orderDate));
        
        // 确保userId不为空
       /* if (userId == null || userId.trim().isEmpty()) {
            throw new TijianAPPException(
                TijianAPPExceptionEnum.SYSTEM_ERROR.getCode(),
                "用户ID不能为空"
            );
        }*/
        
        int count = ordersMapper.countUserOrdersByDate(userId, orderDate);
        //System.out.println("查询结果 - 预约数量: " + count);
        
        if (count > 0) {
            // 用户在当天已有预约，抛出异常
            throw new TijianAPPException(
                TijianAPPExceptionEnum.USER_ALREADY_BOOKED.getCode(),
                TijianAPPExceptionEnum.USER_ALREADY_BOOKED.getMessage()
            );
        }else{
        return new ResponseObject(ResponseObject.SUCCESS_STATUS, ResponseObject.SUCCESS_DESC);
        }
    }
}
